from pyeasyaccept.result.Result import Result
from pyeasyaccept.commom.Configuration import Configuration

class ExpectBetweenCommand:
    """
    It executes the given command and checks
    whether the returned object, is between the interval expected. 
    If so, it returns a result with success message; otherwise, it returns 
    a result with an error message describing the error that was detected.
    
    The Expect command syntax is: 'expectBetween value1 value2 apCommand arg1 arg2 ... argN'
    
    @author: Artur Farias
    """
    
    def execute(self, script, parsedLine):
        """
        This method executes the 'expectBetween' command
        """        
        if(parsedLine.getNumberOfParameters() < 4):
            raise Exception("Expect command syntax is: 'expectBetween value1 value2 applicationCommand arg1 arg2 ... argN'")
        
        try:
            value1 = float(parsedLine.getParameter(1))
            value2 = float(parsedLine.getParameter(2))
        except Exception, ex:
            raise Exception("All the parameters should be float numbers.")
        
        apCommand = parsedLine.getParameter(3)
        
        
        if(self.hasParameters(parsedLine)):
            parameters = parsedLine.subLine(4)
        else:
            parameters = []
        try:
            appMethodResult = float(script.execute(apCommand, parameters))
        except Exception, e:
            exceptionMsg = str(e)
            result = Result(parsedLine, Configuration.ERROR_CODE, exceptionMsg)
            result.addException(None, exceptionMsg)
            return result
        
        if(value1 <= appMethodResult <= value2):
            return Result(parsedLine, Configuration.SUCCESS_CODE, str(appMethodResult))
        
        result = Result(parsedLine, Configuration.ERROR_CODE, str(appMethodResult))
        result.addException(None, 'The result: "' + str(appMethodResult) + '" is not between [' + str(value1) + ',' + str(value2) + ']')
        return result
        
    def hasParameters(self, parsedLine):
        """
        This method informs if a script line has parameters or not
        @param parsedLine: the script line
        """
        return parsedLine.getNumberOfParameters() > 4    
    
    def getParametersNames(self):
        return ["value1", "value2"]    